import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Camera, CameraOptions} from '@ionic-native/camera';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class HeadPortraitSettingProvider {

    private imageSize = 100; // 拍照/从相册选择照片压缩大小
    private qualitySize = 30; // 图像压缩质量，范围为0 - 100

    constructor(public http: HttpClient,
                private camera: Camera,) {
    }

    /**
     * 使用cordova-plugin-camera获取照片
     * @param options
     */
    getPicture(options: CameraOptions = {}): Observable<string> {
        const ops: CameraOptions = Object.assign({
            sourceType: this.camera.PictureSourceType.CAMERA, // 图片来源,CAMERA:拍照,PHOTOLIBRARY:相册
            destinationType: this.camera.DestinationType.FILE_URI, // 默认返回base64字符串,DATA_URL:base64   FILE_URI:图片路径
            quality: this.qualitySize, // 图像质量，范围为0 - 100
            allowEdit: true, // 选择图片前是否允许编辑
            encodingType: this.camera.EncodingType.JPEG,
            targetWidth: this.imageSize, // 缩放图像的宽度（像素）
            targetHeight: this.imageSize, // 缩放图像的高度（像素）
            saveToPhotoAlbum: true, // 是否保存到相册
            correctOrientation: true// 设置摄像机拍摄的图像是否为正确的方向
        }, options);
        return Observable.create(observer => {
            this.camera.getPicture(ops).then((imgData: string) => {
                if (ops.destinationType === this.camera.DestinationType.DATA_URL) {
                    observer.next('data:image/jpg;base64,' + imgData);
                } else {
                    observer.next(imgData);
                }
            }).catch(err => {
                return err;
            });
        });
    }

    /**
     * 通过拍照获取照片
     * @param options
     */
    getPictureByCamera(options: CameraOptions = {}): Observable<string> {
        const ops: CameraOptions = Object.assign({
            sourceType: this.camera.PictureSourceType.CAMERA,
            //destinationType: this.camera.DestinationType.DATA_URL// DATA_URL: 0 base64字符串, FILE_URI: 1图片路径
        }, options);
        return this.getPicture(ops);
    }

    /**
     * 通过图库获取照片
     * @param options
     */
    getPictureByPhotoLibrary(options: CameraOptions = {}): Observable<string> {
        const ops: CameraOptions = Object.assign({
            sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
            //destinationType: this.camera.DestinationType.DATA_URL// DATA_URL: 0 base64字符串, FILE_URI: 1图片路径
        }, options);
        return this.getPicture(ops);
    }
}
